package com.yami.shop.multishop.controller;

import cn.hutool.core.util.StrUtil;
import com.alipay.api.AlipayApiException;
import com.github.binarywang.wxpay.exception.WxPayException;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.bean.param.PayGoodsParam;
import com.yami.shop.bean.param.PayParam;
import com.yami.shop.common.exception.YamiShopBindException;
import com.yami.shop.common.response.ServerResponseEntity;
import com.yami.shop.security.common.manager.PasswordManager;
import com.yami.shop.security.multishop.util.SecurityUtils;
import com.yami.shop.service.ShopDetailService;
import com.yami.shop.service.ShopRechargeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.UnsupportedEncodingException;

@Api(tags = "商家端充值/回调接口")
@RequestMapping("/shop/pay")
@RestController
public class ShopPaymentController {

  @Autowired
  private ShopRechargeService shopRechargeService;
  @Autowired
  private ShopDetailService shopDetailService;
  @Autowired
  private PasswordManager passwordManager;

  @PostMapping("/recharge")
  @ApiOperation("充值请求")
  public ServerResponseEntity<?> pay(@RequestBody @Valid PayParam payParam) {
    ShopDetail detail = shopDetailService.getShopDetailByShopId(SecurityUtils.getShopUser().getShopId());
    if (StrUtil.isBlank(detail.getPayPwd())) {
      throw new YamiShopBindException("yami.shop.pay.password.not.blank");
    }
    String payPwd = passwordManager.decryptPassword(payParam.getPayPwd());
    if (!payPwd.equals(detail.getPayPwd())) {
      throw new YamiShopBindException("yami.shop.pay.password.no.correct");
    }
    return shopRechargeService.doPay(detail, payParam);
  }

  @PostMapping("/notify")
  public ServerResponseEntity<String> notify(HttpServletRequest request,
      @RequestBody(required = false) String xmlData)
      throws WxPayException, AlipayApiException, UnsupportedEncodingException {
    shopRechargeService.notify(request, xmlData);
    return ServerResponseEntity.success();
  }
}